package com.kefu.call.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.call.model.CallCompany;
import com.kefu.call.model.CdrCustomer;
import com.kefu.call.service.CallCompanyService;
import com.kefu.call.service.CdrCustomerService;
import com.kefu.call.http.CtiClient;
import com.kefu.call.util.PwdCheckUtil;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.mybatis.Order;
import com.kefu.sys.service.SysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kefu.common.controller.AbstractBaseController;
import com.kefu.common.result.Result;
import com.kefu.common.result.ResultGenerator;
import com.kefu.common.vo.DeleteVo;
import com.kefu.common.vo.DetailVo;
import com.kefu.call.model.CallSipuser;
import com.kefu.call.service.CallSipuserService;
import com.kefu.call.vo.CallSipuserSearchVo;
import com.kefu.call.vo.CallSipuserInsertVo;
import com.kefu.call.vo.CallSipuserUpdateVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "SIP用户")
@RestController
@RequestMapping("call/sipuser")
public class CallSipuserController extends AbstractBaseController {

    @Autowired
    private CallSipuserService callSipuserService;
    @Autowired
    CtiClient ctiClient;
    @Autowired
    CdrCustomerService cdrCustomerService;
    @Autowired
    SysTenantService sysTenantService;
    @Autowired
    CallCompanyService callCompanyService;

    @PostMapping("/add")
    @ApiOperation(value = "新增SIP用户", notes = "新增SIP用户")
    public Result<String> add(@Validated @RequestBody CallSipuserInsertVo vo) {
        logger.info("新增SIP用户:{}", vo);
        if(!PwdCheckUtil.checkStrongPwd(vo.getPassword())){
            throw new BusinessException("密码必须包含数字、大小写字母、特殊符号且不小于8位");
        }
        String company = vo.getCompany();
        CdrCustomer cdrCustomer = cdrCustomerService.getOne(Wrappers.lambdaQuery(CdrCustomer.class).eq(CdrCustomer::getCompany, vo.getCompany()));
        if (cdrCustomer == null) {
            //生成计费客户
            QueryWrapper<CdrCustomer> query = Wrappers.query();
            query.select("COALESCE(max(oid),1000) oid");
            Integer maxOid = cdrCustomerService.getOne(query).getOid();
            String companyName = sysTenantService.getById(company).getTenantName();
            cdrCustomer = CdrCustomer.builder().oid(maxOid+1).company(company).name(companyName).build();
            cdrCustomerService.save(cdrCustomer);
            //生成呼叫公司配置
            CallCompany callCompany = callCompanyService.getOne(Wrappers.lambdaQuery(CallCompany.class).eq(CallCompany::getFid, company));
            if(callCompany == null){
                callCompanyService.save(CallCompany.builder().fid(company).fName(companyName).build());
            }
        }
        //sip规则，2（呼叫中心产品编码）+ 呼叫计费账号id（4位） + sip号（4位，页面传入）
        StringBuffer sb = new StringBuffer();
        sb.append("2").append(cdrCustomer.getOid()).append(vo.getSipUser());
        Long sipUser = Long.parseLong(sb.toString());
        int num = Math.min(vo.getCreateNum(), 20);
        for (int i = 0; i < 100; i++) {
            if (i >= num) {
                break;
            }
            if (callSipuserService.count(Wrappers.lambdaQuery(CallSipuser.class).eq(CallSipuser::getSipUser, sipUser.toString())) > 0) {
                sipUser = sipUser + 1;
                i = i - 1;
                continue;
            }
            vo.setSipUser(String.valueOf(sipUser));
            CallSipuser info = vo.convert();
            callSipuserService.save(info);
        }
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除SIP用户", notes = "删除SIP用户")
    public Result<String> delete(@Validated @RequestBody DeleteVo delete) {
        logger.info("删除SIP用户:{}", delete);

        callSipuserService.deleteById(delete.getId());
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改SIP用户", notes = "修改SIP用户")
    public Result<String> update(@Validated @RequestBody CallSipuserUpdateVo callSipuserVo) {
        logger.info("修改SIP用户:{}", callSipuserVo);
        if(!PwdCheckUtil.checkStrongPwd(callSipuserVo.getPassword())){
            throw new BusinessException("密码必须包含数字、大小写字母、特殊符号且不小于8位");
        }
        CallSipuser info = callSipuserVo.convert();
        callSipuserService.update(info);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    @ApiOperation(value = "SIP用户详情", notes = "SIP用户详情")
    public Result<CallSipuser> detail(@Validated @RequestBody DetailVo detail) {

        CallSipuser callSipuser = callSipuserService.findById(detail.getId());
        return ResultGenerator.genSuccessResult(callSipuser);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询SIP用户", notes = "查询SIP用户")
    public Result<Page<CallSipuser>> list(@Validated @RequestBody CallSipuserSearchVo search) {

        search.setOrderField("oid");
        search.setOrder(Order.DESC);
        Page<CallSipuser> page = callSipuserService.searchLambdaPage(search);
        return ResultGenerator.genSuccessResult(page);
    }

    @PostMapping("/reloadFsConf")
    @ApiOperation(value = "刷新缓存")
    public Result<String> reloadFsConf() {
        logger.info("刷新呼叫redis数据");

        ctiClient.reloadFsConf("directory");
        return ResultGenerator.genSuccessResult();
    }


}
